package org.mirrentools.attendance.console.router;

import org.mirrentools.attendance.console.service.UsersService;

import io.vertx.core.MultiMap;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.sql.assist.SQLExecute;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;

/**
 * Users的接口服务
 *
 * @author
 */
public class UsersRouter {
  /**
   * 日志工具
   */
  private final Logger LOG = LoggerFactory.getLogger(this.getClass());
  /**
   * 数据服务接口
   */
  private UsersService service;

  private UsersRouter(UsersService service) {
    super();
    this.service = service;
  }

  /**
   * 启动服务
   *
   * @param router  Router
   * @param execute 数据执行器
   */
  public static void startService(Router router, SQLExecute<JDBCClient> execute) {
    UsersRouter instance = new UsersRouter(UsersService.create(execute));
    // 获取用户信息
    router.route("/api/users/get").handler(instance::get);
    // 验证用户token
    router.route("/api/users/checkToken").handler(instance::checkToken);
    // 获取用户列表
    router.route("/admin/api/find/users").handler(instance::findUsers);
  }

  /**
   * 监测用户的token是否正确
   */
  private void checkToken(RoutingContext rct) {
    MultiMap params = rct.request().params();
    if (LOG.isDebugEnabled()) {
      LOG.debug("执行获取数据[UsersService.get]-->请求参数:\n" + params);
    }
    service.checkToken(rct, res -> {
      rct.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=utf-8").end(res.result().toBuffer());
    });
  }

  /**
   * 获取用户信息
   */
  private void get(RoutingContext rct) {
    MultiMap params = rct.request().params();
    if (LOG.isDebugEnabled()) {
      LOG.debug("执行获取数据[UsersService.get]-->请求参数:\n" + params);
    }
    service.get(rct, res -> {
      rct.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=utf-8").end(res.result().toBuffer());
    });
  }
  /**
   * 管理员获取用户列表
   */
  private void findUsers(RoutingContext rct) {
    MultiMap params = rct.request().params();
    if (LOG.isDebugEnabled()) {
      LOG.debug("执行获取数据[UsersService.findUsers]-->请求参数:\n" + params);
    }
    service.findUsers(rct, res -> {
      rct.response().putHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=utf-8").end(res.result().toBuffer());
    });
  }

  /**
   * 新增用户信息
   */
  private void post(RoutingContext rct) {
    MultiMap params = rct.request().params();
    if (LOG.isDebugEnabled()) {
      LOG.debug("执行获取数据[UsersService.get]-->请求参数:\n" + params);
    }
    service.post(rct, res -> {
      rct.response().setStatusCode(201).putHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=utf-8").end(res.result().toBuffer());
    });
  }
}
